package com.sservice.web.controller.pc;

import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.common.Constants;
import com.sservice.commonBusiness.e.DataR;
import com.sservice.commonBusiness.mapper.CommentMapper;
import com.sservice.commonBusiness.mapper.FileMapper;
import com.sservice.commonBusiness.service.CategoryService;
import com.sservice.commonBusiness.service.CommentService;
import com.sservice.commonBusiness.service.DataRService;
import com.sservice.commonBusiness.vo.CategoryVo;
import com.sservice.commonBusiness.vo.FileVo;
import com.sservice.model.entity.Info;
import com.sservice.model.entity.UserWx;
import com.sservice.model.vo.InfoVo;
import com.sservice.model.vo.UserWxVo;
import com.sservice.service.service.IComService;
import com.sservice.service.service.IInfoService;
import com.sservice.service.service.IUserWxService;
import com.sservice.service.service.wx.WxMsg;
import com.sservice.urp.entity.Com;
import com.sservice.web.common.StringUtils;
import com.sservice.web.controller.admin.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/info")
public class InfoPcController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IInfoService dataService;


    @Autowired
    private IComService iComService;

    @Autowired
    CommentService commentService;
    @Autowired
    CommentMapper commentMapper;

    @Autowired
    DataRService dataRService;
    @Autowired
    FileMapper fileMapper;
    @Autowired
    CategoryService categoryService;

    /**
     * 法治的地图，律师人员
     * 基于片区进行数据的
     *
     * @param arg
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/categoryByPianQu", method = RequestMethod.GET)
    public ListResult<Object> categoryByPianQu(CategoryVo arg, HttpSession session) {

        String comIds = dataService.getPianQu(arg.getComId());
        String[] ids = comIds.split(",");
        List list = categoryService.page(arg);
        for (String id : ids
                ) {
            if (!id.equals(arg.getComId())) {
                arg.setComId(id);
                List list1 = categoryService.page(arg);
                list.addAll(list1);
            }
        }
        ListResult<Object> res = new ListResult(true, list);
        return res;
    }

    @Autowired
    WxMsg wxMsg;
    @Autowired
    UserController userController;
    @Autowired
    IUserWxService iUserWxService;

    /**
     * 创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> create(Info arg, String fileIds, HttpSession session, HttpServletRequest request) {
        UserWx user_ = (UserWx) session.getAttribute(Constants.CURRENT_SP);
        if (arg.getType1() == null) {
            arg.setType1(1);
        }
        if (user_ != null)
            arg.setAuthorId(String.valueOf(user_.getId()));
        if (StringUtils.isBlank(arg.getComId())) { // 前端指定公众号平台，则自动记录
            Com com = iComService.judgeRegion(arg.getCategory());
            if (com != null) { // 定位区域问题
                arg.setComId(com.getId().toString());
            } else {
                arg.setComId("3");
            }
        }
        int service_res = dataService.insertSelective(arg);
        if (Integer.valueOf(InfoVo.lawHelp).equals(arg.getType1())) { //法律援助
            DataR dataR = new DataR();//
            dataR.setType1("wx-" + InfoVo.lawHelp + "-" + arg.getComId());
            List<UserWxVo> list = iUserWxService.queryDrLink(dataR);
            List<String> openIds = wxMsg.getOpenIds(list);
            wxMsg.applyLawHelpNoticeToWorkers(arg.getComId(), arg.getId().toString(), user_.getNickName(), openIds, arg.getContent());
        }
        if (Integer.valueOf(InfoVo.lawAsk).equals(arg.getType1())) { //法律咨询
            DataR dataR = new DataR();//
            dataR.setType1("wx-" + InfoVo.lawAsk + "-" + arg.getComId() + "-" + arg.getStreetId());
            List<UserWxVo> list = iUserWxService.queryDrLink(dataR);//
            List<String> openIds = wxMsg.getOpenIds(list);
            //通知街道司法所所长进行问题回复
            wxMsg.applyLawAskNoticeToStreetLawLeader(arg.getComId(), arg.getStreetId() + "", openIds, arg.getContent());
            //wxMsg.applyLawAskNoticeToWorkers(arg.getComId(), openIds, arg.getContent());
        }
        if (Integer.valueOf(InfoVo.ask).equals(arg.getType1())) { //在线咨询
            DataR dataR = new DataR();//
            dataR.setType1("wx-" + InfoVo.ask + "-" + arg.getComId());
            List<UserWxVo> list = iUserWxService.queryDrLink(dataR);
            List<String> openIds = wxMsg.getOpenIds(list);
            wxMsg.applyAskNoticeToWorkers(arg.getComId(), user_.getNickName(), openIds, arg.getContent());
        }
        if (Integer.valueOf(InfoVo.sugguest).equals(arg.getType1())) { //投诉建议
            DataR dataR = new DataR();//
            dataR.setType1("wx-" + InfoVo.sugguest + "-" + arg.getComId());
            List<UserWxVo> list = iUserWxService.queryDrLink(dataR);
            List<String> openIds = wxMsg.getOpenIds(list);
            wxMsg.applySuggestNoticeToWorkers(arg.getComId(), openIds, arg.getContent());
        }
        if (Integer.valueOf(InfoVo.compose).equals(arg.getType1())) { //人民调解
            DataR dataR = new DataR();//
            dataR.setType1("wx-" + InfoVo.compose + "-" + arg.getComId());
            List<UserWxVo> list = iUserWxService.queryDrLink(dataR);
            List<String> openIds = wxMsg.getOpenIds(list);
            logger.debug(arg.getComId());
            logger.debug(user_.getNickName());
            logger.debug(openIds == null ? "NULL" : "");
            logger.debug(Arrays.toString(openIds.toArray()));
            logger.debug(arg.getContent());
            wxMsg.applyComposeNoticeToWorkers(arg.getComId(), user_.getNickName(),
                    "工作人员", openIds, arg.getContent());
        }
        if (StringUtils.isNoneBlank(fileIds)) { //
            String[] fileIds1 = fileIds.split(",");
            List dar = new ArrayList();
            for (String fileId : fileIds1) {
                DataR dataR = new DataR();
                dataR.setType1("type-img-" + arg.getType1());
                dataR.setSourceId(arg.getId());
                dataR.setTargetId(Integer.valueOf(fileId));
                dar.add(dataR);
            }
            dataRService.addBatch(dar);
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    /**
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult delete(Info arg, HttpSession session) {
        UserWx sp = (UserWx) session.getAttribute(Constants.CURRENT_SP);
        Info info = dataService.selectByPrimaryKey(arg.getId());
        if (info == null) {
            return new BaseResult(true, "非法操作！", 403);
        } else if (String.valueOf(sp.getId()).equals(info.getAuthorId())) { //当前登录用户编辑
            int service_res = dataService.deleteByPrimaryKey(arg.getId());
            return new BaseResult(true, service_res);
        } else {
            return new BaseResult(true, "该作品不是您的个人作品，无权删除！", 403);
        }
    }

    /**
     * 故事更新
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(Info arg) {
        arg.setType1(1);
        int service_res = dataService.updateByPrimaryKeySelective(arg);
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<Info> get(Info arg) {
        Info service_res = dataService.selectByPrimaryKey(arg.getId());
        BaseResult<Info> res = new BaseResult<Info>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public BaseResult<Info> detail(Info arg) {
        Info service_res = dataService.selectByPrimaryKey(arg.getId());
        BaseResult<Info> res = new BaseResult<Info>(true, service_res);
        return res;
    }

    /***
     *
     * type1=5 团队作品
     * type1=2 导师作品
     * type1=0 资讯
     * type1=1 竞拍故事
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(InfoVo arg, HttpSession session) {
        Integer it = Integer.valueOf(1);
        Integer it5 = Integer.valueOf(5);
        if (arg.getAuthorId() != null && "MY".equals(arg.getAuthorId()) && (
                it.equals(arg.getType1()) || it5.equals(arg.getType1()))) {
            UserWx salePerson = (UserWx) session.getAttribute(Constants.CURRENT_SP);
            if (salePerson != null) {
                arg.setAuthorId(String.valueOf(salePerson.getId()));
            }
        }
        List<Info> list = dataService.queryByPage(arg);
        int total = dataService.queryCount(arg);

        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryPlain", method = RequestMethod.GET)
    public ListResult queryPlain(InfoVo arg, HttpSession session) {
        UserWx user_ = (UserWx) session.getAttribute(Constants.CURRENT_SP);
        if (arg.getType1() == null) {
            arg.setType1(1);
        }
        if (user_ != null)
            arg.setAuthorId(String.valueOf(user_.getId()));
//        Com com = iComService.judgeRegion(arg.getCategory());
//        if (com != null) { // 定位区域问题
//            arg.setComId(com.getId().toString());
//        }

        List<InfoVo> list = dataService.queryPlainByPage(arg);
        int total = dataService.countPlainByPage(arg);
        for (InfoVo info : list
                ) {
            FileVo fileVo = new FileVo();
            fileVo.setDrType(arg.getType1().toString());
            fileVo.setSourceId(info.getId().toString());
            info.setImgs(fileMapper.queryDrByPage(fileVo));
        }
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryfdPlain", method = RequestMethod.GET)
    public ListResult queryfdPlain(InfoVo arg, HttpSession session) {
//        UserWx user_ = (UserWx) session.getAttribute(Constants.CURRENT_SP);
        if (arg.getType1() == null) {
            arg.setType1(1);
        }
//        if (user_ != null&&!"noauthor".equals(arg.getAuthorId())){
//            arg.setAuthorId(String.valueOf(user_.getId()));
//        }else {
//            arg.setAuthorId(null);
//        }
        List<InfoVo> list = dataService.queryfdPlainByPage(arg);
        int total = dataService.querydrCount(arg);
        for (InfoVo info : list
                ) {
            FileVo fileVo = new FileVo();
            fileVo.setDrType("type-img-" + arg.getType1());
            fileVo.setSourceId(info.getId().toString());
            info.setImgs(fileMapper.queryDrByPage(fileVo));
        }
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }


}
